package com.lxk.util;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.lxk.util.exception.GlobalException;
import com.lxk.vo.result.CodeMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author JohnSoybean
 * @create 2020/3/24 17:50
 * @description
 */
@SuppressWarnings("deprecation")
public class OSSClientUtil {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /*
     * 个人oss
     */
//    private String endpoint = "oss-cn-hangzhou.aliyuncs.com";
//    private String accessKeyId = "LTAI4FgR5CJZy9PLU41jCVP9";
//    private String accessKeySecret = "0OZeVvxzJtITZLhFTiNJZECbIgW2yS";
//    private String bucketName = "qianjia-vedio";

    /*
     *公司oss
     */
	private String endpoint = "oss-cn-hangzhou.aliyuncs.com";
	private String accessKeyId = "LTAI4FeoPyWovFmM4EucPfXx";
	private String accessKeySecret = "abcgpJubiH1h1HxVvpqk1TY6HzNcUz";
    private String bucketName = "qinajia-life"; //注意：打错了


    private String imageDir = "picture/";
    private String vedioDir = "vedio/";

    private OSSClient ossClient;


    public OSSClientUtil() {
        //注意： 专有云、专有域环境必须要使用ClientConfiguration的对象传入参数，不然会报错。
        //创建ClientConfiguration实例，按照您的需要修改默认参数。
        ClientConfiguration conf = new ClientConfiguration();
        //关闭CNAME选项。
        conf.setSupportCname(false);
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf);
    }

    //初始化
    public void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    //销毁
    public void destory() {
        ossClient.shutdown();
    }

    /**
     * 文件种类
     *
     * @param file
     * @return
     */
    public Integer getType(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        logger.info(suffix);
        if (suffix.equals("bmp") || suffix.equals("png") || suffix.equals("gif") || suffix.equals("jpeg") || suffix.equals("jpg")) {
            return 1;
        } else if (suffix.equals("mov") || suffix.equals("mp4") || suffix.equals("avi")) {
            return 2;
        } else {
            return 0;
        }
    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws Exception
     */
    public String uploadImg2Oss(MultipartFile file) {
        if (file.getSize() > 10 * 1024 * 1024) {
            throw new GlobalException(CodeMsg.IMAGE_SIZE_OUT);
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        String fileName = randomFileName(suffix);
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, fileName, imageDir);
            return imageDir + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException(CodeMsg.UPLOAD_IMAGE_FAIL);
        }
    }


    /**
     * 上传视频
     *
     * @param file
     * @return
     * @throws Exception
     */
    public String uploadVedio2Oss(MultipartFile file) {
        if (file.getSize() > 50 * 1024 * 1024) {
            throw new GlobalException(CodeMsg.VEDIO_SIZE_OUT);
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        String fileName = randomFileName(suffix);
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, fileName, vedioDir);
            return vedioDir + fileName;
        } catch (Exception e) {
            throw new GlobalException(CodeMsg.UPLOAD_VEDIO_FAIL);
        }
    }


    /**
     * 获得外部访问的URL链接 
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
//		// 设置URL过期时间为20年 3600l* 1000*24*365*20  
//		Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 20);
//		// 生成URL  
//		URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
//		if (url != null) {
//			return url.toString();
//		}
        StringBuffer sb = new StringBuffer();
        sb.append("http://").append(bucketName).append(".").append(endpoint).append("/").append(key);
        String url = sb.toString();
        return url;
    }


//内部工具方法

    /**
     * 上传到OSS服务器 如果同名文件会覆盖服务器上的
     *
     * @param instream            文件流
     * @param fileName            文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    private String uploadFile2OSS(InputStream instream, String fileName, String filedir) {
        String ret = "";
        try {
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf(".") + 1)));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //System.out.println("开始上传文件");
            // 上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
            //PutObjectResult putResult = ossClient.putObject(bucketName,  fileName, instream, objectMetadata);
            //System.out.println("上传成功");
            ret = putResult.getETag();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 判断OSS服务文件上传时文件的contentType 
     *
     * @param filenameExtension 文件后缀
     * @return String
     */
    private static String getcontentType(String filenameExtension) {
        if (filenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (filenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")
                || filenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (filenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (filenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (filenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (filenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        if (filenameExtension.equalsIgnoreCase("mov")) {
            return "video/quicktime";
        }
        if (filenameExtension.equalsIgnoreCase("mp4")) {
            return "video/mp4";
        }
        if (filenameExtension.equalsIgnoreCase("avi")) {
            return "video/x-msvideo";
        }
        return "image/jpeg";
    }


    /**
     * 生成随机文件名
     *
     * @param suffix
     * @return
     */
    public static String randomFileName(String suffix) {
        String uuid = UUID.randomUUID().toString();
        String filePath = uuid + suffix;
        return filePath;
    }
}
